import { useCallback, useRef, useState } from 'react';

import chatService from '@/api/services/chatService';
import { getChatInitReq, PaginationResponse } from '@/common';
import { useScrollPagination } from '@/hooks/use-pagination/useVirtualScrollPagination';
import {
  ComponentRef as ChatComponentRef,
  ChatSiteItemType,
  SendPromptFnType,
} from '@/pages/chat/tools/constants';
import { getNanoid } from '@/pages/chat/tools/tools';
import { ChatStatusEnum, GetChatTypeEnum } from '@/types/chat/constants';
import { PluginRunBoxTabEnum } from '@/types/workflow/components/PluginRunBox/constants';
import { eventBus, EventNameEnum } from '@/utils/eventBus';

export const useChat = (params?: { chatId?: string; appId: string; type?: GetChatTypeEnum }) => {
  const ChatBoxRef = useRef<ChatComponentRef>(null);
  // const variablesForm = useForm<ChatBoxInputFormType>();
  const [variables, setVariables] = useState<Record<string, any>>({});
  // plugin
  const [pluginRunTab, setPluginRunTab] = useState<PluginRunBoxTabEnum>(PluginRunBoxTabEnum.input);

  const resetVariables = useCallback(
    (props?: { variables?: Record<string, any> }) => {
      const { variables = {} } = props || {};

      // 重置为输入为空
      const data = { ...variables, ...props?.variables };
      Object.keys(data).forEach((key) => {
        data[key] = '';
      });

      setVariables({
        ...data,
        ...variables,
      });
    },
    [setVariables],
  );

  const clearChatRecords = useCallback(() => {
    // 使用 Object.keys 替代 for...in，避免遍历原型链
    setVariables((prev) => {
      const cleared = { ...prev };
      Object.keys(cleared).forEach((key) => {
        cleared[key] = '';
      });
      return cleared;
    });

    ChatBoxRef.current?.restartChat?.();
  }, [setVariables, ChatBoxRef]);

  const {
    data: chatRecords,
    ScrollData,
    setData: setChatRecords,
    total: totalRecordsCount,
  } = useScrollPagination(
    async (data: getChatInitReq): Promise<PaginationResponse<ChatSiteItemType>> => {
      if (!data?.appId && !data?.chatId) {
        return {
          list: [],
          total: 0,
        };
      }
      const res = await chatService.ChatRecords(data);

      // 首次加载时滚动到底部
      if (data.offset === 0) {
        requestAnimationFrame(() => {
          ChatBoxRef?.current?.scrollToBottom?.();
        });
      }

      return {
        ...res,
        list: res.list.map((item: { dataId: any; status: ChatStatusEnum }) => ({
          ...item,
          dataId: item.dataId || getNanoid(),
          status: ChatStatusEnum.finish,
        })),
      };
    },
    {
      pageSize: 10,
      refreshDeps: [params],
      params,
      scrollLoadType: 'top',
    },
  );

  return {
    ChatBoxRef,
    variables,
    pluginRunTab,
    setPluginRunTab,
    clearChatRecords,
    resetVariables,
    chatRecords,
    ScrollData,
    setChatRecords,
    totalRecordsCount,
  };
};

export const onSendPrompt: SendPromptFnType = (e) => eventBus.emit(EventNameEnum.sendQuestion, e);
